package com.atguigu.resolver;

import com.atguigu.exception.MyException;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author ：HB
 * @date ：Created in 2020/10/30 19:54
 * @description：自定义异常类的解析器
 * 自定义异常的处理步骤：
 *  1. 创建异常处理器类实现HandlerException
 *  2. 配置异常处理器
 *  3. 编写异常页面
 *  4. 测试异常跳转
 */
public class MyExceptionResolver implements HandlerExceptionResolver{
    /**
     *
     * @param request
     * @param response
     * @param handler
     * @param exception:异常对象
     * @return：返回值ModelAndView：跳转到错误视图的信息
     */
    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception exception) {
        //返回值
        ModelAndView mav = new ModelAndView();
        //判断异常的类型
        if (exception instanceof MyException) {
            mav.addObject("info","自定义的异常");
        }else if(exception instanceof ClassCastException){
            mav.addObject("info","类型转换异常");
        }
        mav.setViewName("error");
        return mav;
    }
}
